package demo.java.java8.Lambdas.demo7;

import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;
import java.util.stream.LongStream;

import com.twitter.jsr166e.ForkJoinPool;

public class ForkJoinSumCalculator extends RecursiveTask<Long> {

	private final int start;
	private final int end;
	private final long[] number;
	
	private static final long THRESHOLD = 10_000;
	
	public ForkJoinSumCalculator(long [] numbers) {
		this(numbers, 0, numbers.length);
	}
	public ForkJoinSumCalculator(long[] numbers,int start,int end) {
		this.number=numbers;
		this.start=start;
		this.end=end;
	}
	
	@Override
	protected Long compute() {
		int length = end-start;
		if(length<=THRESHOLD){
			return computeSequentially();
		}
		ForkJoinSumCalculator leftTask=new ForkJoinSumCalculator(number, start, start+length/2);
		ForkJoinSumCalculator rightTask=new ForkJoinSumCalculator(number, start+length/2, end);
		Long rightResult=rightTask.compute();
		Long leftResult=leftTask.join();
		return leftResult+rightResult;
	}

	
	private long computeSequentially(){
		long sum = 0;
		for(int i=start;i<end;i++){
			sum+=number[i];
		}
		return sum;
	}
	
}
